package com.junxonline.instant.admin.service.log.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junxonline.instant.dao.entity.model.log.LogOperation;
import com.junxonline.instant.dao.entity.vo.log.LogOperationVO;
import com.junxonline.instant.dao.mapper.log.LogOperationMapper;
import com.junxonline.instant.admin.service.log.LogOperationService;
import com.junxonline.instant.common.constant.CommonConstant;
import com.junxonline.instant.common.constant.DataSourceConstant;
import com.junxonline.instant.common.entity.common.CommonReqPage;
import com.junxonline.instant.common.entity.common.CommonRespPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 操作日志接口实现类
 *
 * @author JunX
 * @date 2021-06-24
 */
@Service
@Transactional
public class LogOperationServiceImpl extends ServiceImpl<LogOperationMapper, LogOperation> implements LogOperationService {

    @Autowired
    private LogOperationMapper logOperationMapper;

    /**
     * 查询操作日志列表
     *
     * @param vo      请求参数
     * @param wrapper 条件查询器
     * @return CommonRespPage<LogOperation>
     */
    @Override
    @DS(DataSourceConstant.SHARDING)
    public CommonRespPage<LogOperation> queryList(CommonReqPage<LogOperationVO> vo, QueryWrapper<LogOperation> wrapper) {
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getName()), "t.name", vo.getQueryParams().getName());
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getUsername()), "u.username", vo.getQueryParams().getUsername());
        wrapper.eq(vo.getQueryParams().getType() != null, "t.type", vo.getQueryParams().getType());
        wrapper.eq(vo.getQueryParams().getStatus() != null, "t.status", vo.getQueryParams().getStatus());
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getUserIp()), "t.user_ip", vo.getQueryParams().getUserIp());
        if (vo.getQueryParams().getOperationTime() != null) {
            wrapper.between("t.operation_time"
                    , DateUtil.parseDateTime(vo.getQueryParams().getOperationTime()[0] + CommonConstant.QUERY_TIME_APPEND_START_TIME)
                    , DateUtil.parseDateTime(vo.getQueryParams().getOperationTime()[1] + CommonConstant.QUERY_TIME_APPEND_END_TIME));
        }
        return CommonRespPage.success(logOperationMapper.queryList(new Page<>(vo.getPage(), vo.getPageSize()), wrapper));
    }
}
